package echo.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author： zhangnan
 * @date： 2025/4/8 18:37
 * @description： TODO
 * @modifiedBy：自定义的echo 处理器类，继承自 ChannelInboundHandlerAdapter
 * @version: 1.0
 */
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    private final AtomicInteger workerThreadCounter;

    // 构造函数，接收 workerThreadCounter
    public EchoServerHandler(AtomicInteger workerThreadCounter) {
        this.workerThreadCounter = workerThreadCounter;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx,Object msg){
        // 打印当前处理消息的线程名称和处理次数
        System.out.println("Processing message on thread: " + Thread.currentThread().getName() + ", Worker thread counter: " + workerThreadCounter.incrementAndGet());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 将接收到的消息原样写回客户端
        ctx.write(msg);
//        ctx.writeAndFlush();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx){
        // 将缓冲区中的数据刷新到客户端
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
        // 捕获并打印异常信息
        cause.printStackTrace();
        // 关闭通道以释放资源
        ctx.close();
    }

}
